#!/usr/bin/env python
# -*- coding: UTF-8 -*-

from twisted.web import server, resource
from twisted.internet import reactor
from resource.user_resource import UserResource
from resource.item_resource import ItemResource
from resource.websocket_resource import WebSocketResource
from game_state import GameState
from resource.wechat_resource import WeChatUserInfoResource, WeChatLogoutResource, WeChatTokenVerifyResource, \
    WeChatLoginResource
from utility.sync_service import DatabaseSyncService
from autobahn.twisted.resource import WebSocketResource as AutobahnWebSocketResource
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def shutdown_handler(game_state, sync_service):
    """程序关闭时的处理函数"""
    logging.info("正在关闭服务器...")
    # 停止同步服务
    sync_service.stop_sync()
    # 最后一次同步所有数据
    success_count = game_state.sync_all_users_to_db()
    logging.info(f"最终数据同步完成，成功同步 {success_count} 个玩家数据")
    # 关闭数据库连接
    if hasattr(game_state.mongo_db, 'close'):
        game_state.mongo_db.close()
    logging.info("服务器已关闭")

# 创建中间层级资源
api_resource = resource.Resource()
wechat_resource = resource.Resource()
logic_resource = resource.Resource()

# 创建根资源
root = resource.Resource()
game_state = GameState()

# 装载资源树
root.putChild(b"api", api_resource)
api_resource.putChild(b"wechat", wechat_resource)
api_resource.putChild(b"logic", logic_resource)

# 添加具体的资源
wechat_resource.putChild(b'login', WeChatLoginResource(game_state))  # 微信授权登录
wechat_resource.putChild(b'verify', WeChatTokenVerifyResource(game_state))  # 验证token
wechat_resource.putChild(b'logout', WeChatLogoutResource(game_state))  # 登出
logic_resource.putChild(b'user', UserResource(game_state))  # 查询玩家信息
logic_resource.putChild(b'item', ItemResource(game_state))  # 查询物品信息
logic_resource.putChild(b'user', WeChatUserInfoResource(game_state))  # 获取用户信息

# 添加WebSocket支持
websocket_resource = WebSocketResource(game_state)
wechat_resource.putChild(b'websocket', AutobahnWebSocketResource(websocket_resource.get_ws_factory()))

# 启动数据库同步服务
sync_service = DatabaseSyncService(game_state, interval=30)  # 每30秒同步一次
sync_service.start_sync()

# 监听端口
site = server.Site(root)
reactor.listenTCP(8080, site)
logging.info("HTTP短连接游戏服务器运行在端口8080...")
logging.info("WebSocket服务器可通过 ws://localhost:8080/websocket 访问")

# 注册关闭处理函数
reactor.addSystemEventTrigger('before', 'shutdown', shutdown_handler, game_state, sync_service)

reactor.run()
